package service;

import beans.CarInfo;
import beans.QueryParamInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.HttpUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by yanglq on 2018/4/8.
 */
public class APIService {
    private final static Logger logger = LoggerFactory.getLogger(APIService.class);

    private static String accessToken;

    private static String userName;
    private static String getTokenUrl;
    private static String getCaraccessUrl;
    private static String saveLogUrl;


    public void initConfig() throws IOException {
        try {
            Properties prop = new Properties();
            InputStream in = this.getClass().getResourceAsStream("/sysinfo.properties");
            prop.load(in);
            userName = prop.getProperty("userName");
            getTokenUrl = prop.getProperty("getTokenUrl");
            getCaraccessUrl = prop.getProperty("getCaraccessUrl");
            saveLogUrl = prop.getProperty("saveLogUrl");
            logger.info("系统参数加载文件加载完成");
        } catch (Exception e) {
            logger.error("系统参数加载文件加载完成加载失败, 请确认文件是否存在");
            e.printStackTrace();
            throw e;
        }

    }

    public String getToken() throws IOException {
        // 接口参数列表, 不同API请替换相应参数
        Map<String, String> params = new HashMap<>();
        // 登录用户名
        params.put("userName", userName);
        // 生成URL地址，不需要修改
        String URL = HttpUtil.generateURL(params, getTokenUrl);
        // 发送HTTP GET 请求
        accessToken = doGetToken(URL);
        logger.info("获取到的token为：{}，获取时间为{}", accessToken, new Date());
        return accessToken;
    }

    public List<CarInfo> getCarAccess(QueryParamInfo info) throws IOException {
        // 接口参数列表, 不同API请替换相应参数
        Map<String, String> params = new HashMap<>();
//        params.put("entranceChannelIds", "");
//        params.put("exitusChannelIds", "");
        params.put("queryTimeBegin", info.getQueryTimeBegin());
        params.put("queryTimeEnd", info.getQueryTimeEnd());
//        params.put("carNum", "6181385B");
//        params.put("pageNum", "1");
//        params.put("pageSize", String.valueOf(info.getPageSize()));
        // 生成URL地址，不需要修改
        String URL = HttpUtil.generateURL(params, getCaraccessUrl);
        // 发送HTTP GET 请求
        return dogetCarAccess(URL, accessToken);
    }

    private List<CarInfo> dogetCarAccess(String url, String token) throws IOException {
        List<CarInfo> infos = new ArrayList<>();
        CarInfo carInfo;
        JSONObject jo = HttpUtil.httpGet(url, token);
        if (jo != null) {
            JSONArray datas = jo.getJSONObject("data").getJSONArray("pageData");
            for (Object data : datas
                    ) {
                carInfo = (CarInfo) JSONObject.toBean((JSONObject) data, CarInfo.class);
                infos.add(carInfo);
            }

        }
        return infos;
    }


    private String doGetToken(String url) throws IOException {
        JSONObject jo = HttpUtil.httpGet(url, null);
        if (jo != null) {
            return jo.getJSONObject("data").getString("accessToken");
        } else
            return null;
    }

    public void dosaveLog(List<NameValuePair> info) throws IOException {
        HttpUtil.httpPost(saveLogUrl, info);
    }

}
